package com.xiaobing.gateway.filter;


import com.alibaba.fastjson2.JSONObject;
import com.xiaobing.common.constant.CacheConstants;
import com.xiaobing.common.core.JwtUtils;
import com.xiaobing.common.core.SecurityConstants;
import com.xiaobing.common.core.TokenConstants;
import com.xiaobing.common.povo.LoginUser;
import com.xiaobing.common.res.HttpStatusCode;
import com.xiaobing.common.utils.IgnoreWhite;
import com.xiaobing.common.utils.ServletUtils;
import com.xiaobing.common.utils.StringUtils;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 网关过滤器
 * <p>
 * xulk
 */


@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {


    @Resource
    public RedisTemplate redisTemplate;

//    @Resource
//    private TokenService tokenService;


    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;


    private final static long expireTime = CacheConstants.EXPIRATION;

    private final static Long MILLIS_MINUTE_TEN = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, IgnoreWhite.getWhites())) {
            return chain.filter(exchange);
        }

        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            return webFluxResponseWriter(exchange.getResponse(), "application/json", HttpStatus.UNAUTHORIZED, "令牌不能为空!", HttpStatusCode.UNAUTHORIZED);
        }
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token);
            if (claims == null) {
                return webFluxResponseWriter(exchange.getResponse(), "application/json", HttpStatus.UNAUTHORIZED, "令牌已过期或验证不正确", HttpStatusCode.UNAUTHORIZED);
            }
        } catch (Exception e) {
            return webFluxResponseWriter(exchange.getResponse(), "application/json", HttpStatus.UNAUTHORIZED, "令牌不合法！", HttpStatusCode.UNAUTHORIZED);
        }

        String userkey = JwtUtils.getUserKey(claims);

        boolean islogin = redisTemplate.hasKey(getTokenKey(userkey));
        if (!islogin) {
            return webFluxResponseWriter(exchange.getResponse(), "application/json", HttpStatus.UNAUTHORIZED, "登录状态已过期", HttpStatusCode.FORBIDDEN);
        }


        // TODO  处理token的有效期  userkey
        String tokenKey =  CacheConstants.LOGIN_TOKEN_KEY + userkey;
        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(  tokenKey );
        verifyToken(loginUser);

        String userid = JwtUtils.getUserId(claims);
        String username = JwtUtils.getUserName(claims);
        if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)) {
            return webFluxResponseWriter(exchange.getResponse(), "application/json", HttpStatus.UNAUTHORIZED, "令牌验证失败", HttpStatusCode.UNAUTHORIZED);
        }


        // 设置用户信息到请求
        addHeader(mutate, SecurityConstants.USER_KEY, userkey);
        addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid);
        addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username);
        // 内部请求来源参数清除
        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());


/*        MultiValueMap<String, String> params = request.getQueryParams();
        // 2.获取参数中的 authorization 参数
        String auth = params.getFirst("authorization");
        if (StringUtils.isBlank(auth)) {
            // 4.是，放行
            return chain.filter(exchange);
        }
        // 3.判断参数值是否等于 admin
        if ("admin".equals(auth)) {
            // 4.是，放行
            return chain.filter(exchange);
        }
        // 5.否，拦截
        // 5.1.设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        // 5.2.拦截请求
        return exchange.getResponse().setComplete();*/
    }


    /**
     * 验证令牌有效期，相差不足120分钟，自动刷新缓存
     *
     * @param loginUser
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }


    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        // 移除密码
        if( loginUser.getSysUser() != null ){
            loginUser.getSysUser().setPassword(null);
        }
        redisTemplate.opsForValue().set(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }





    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }


    @Override
    public int getOrder() {
        return -200;
    }

    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }


    public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, HttpStatus status, Object value, int code) {
        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
        JSONObject json = new JSONObject();
        json.put(code + "", value.toString());
        DataBuffer dataBuffer = response.bufferFactory().wrap(json.toJSONString().getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }


}

